package com.puhui.lib.base.dialog

import android.R
import android.app.Activity
import android.content.DialogInterface
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.view.*
import androidx.annotation.CallSuper
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.fragment.app.FragmentManager
import androidx.lifecycle.*
import com.puhui.lib.utils.reportCaughtException
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe

/**
 * Description: 弹窗基类
 * Data：2019/9/30 0030-上午 10:01
 *
 */
abstract class BaseDialogFragment : DialogFragment(), LifecycleObserver {

    private var showLiveData: MutableLiveData<Boolean>? = null
    private var syncLifecycle = false

    open var onDismissListener: DialogInterface.OnDismissListener? = null

    @CallSuper
    override fun onDismiss(dialog: DialogInterface) {
        super.onDismiss(dialog)
        onDismissListener?.onDismiss(dialog)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setStyle(STYLE_NO_TITLE, getStyle())

        lifecycle.addObserver(this)
        if (isNeedEventBus() && !EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this)
        }
    }

    open fun isNeedEventBus(): Boolean {
        return false
    }

    override fun onDestroy() {
        if (isNeedEventBus()) {
            EventBus.getDefault().unregister(this)
        }
        super.onDestroy()
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    fun onLifeDestroy() {
        onDestroy()
    }

    @Subscribe
    fun defaultEventMethod(event: EventBus) {
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
    ): View? {
        val view = inflater.inflate(getLayoutRes(), container)
        val backgroundRes = getBackgroundRes()
        backgroundRes?.let { view.setBackgroundResource(it) }
        return view
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        if (savedInstanceState != null && dismissWhenRecreate()) {
            dismiss()
            return
        }
        init(savedInstanceState)
    }

    open fun show(activity: Activity?) {
        //如果所依赖的Activity已经销毁，则不显示
        if (activity?.isFinishing == true) return

        if (activity is FragmentActivity) {
            show(activity.supportFragmentManager, activity.javaClass.simpleName)
        } else {
            reportCaughtException(RuntimeException("activity = $activity,it's not FragmentActivity"))
        }
    }

    open fun show(fragment: Fragment?) {
        //如果所依赖的Fragment已经不存在，则不显示
        if (fragment?.isVisible != true) return

        show(fragment.childFragmentManager, fragment.javaClass.simpleName)
    }

    override fun dismiss() {
        if (syncLifecycle) {
            syncLifecycle = false
            showLiveData?.value = false
        } else {
            // 用dismiss的话，在dialog显示状态时，如果切换APP或回到桌面，则会报错如下：
            // IllegalStateException: Can not perform this action after onSaveInstanceState
            // dismissAllowingStateLoss()该方法内部会调用commitAllowingStateLoss()
            super.dismissAllowingStateLoss()
        }
    }

    override fun show(fragmentManager: FragmentManager, tag: String?) {
        if (isAdded) {
            return
        }
        if (syncLifecycle) {
            showLiveData?.value = true
        } else {
            super.show(fragmentManager, tag)
        }
    }

    override fun onStart() {
        super.onStart()
        dialog?.window?.apply {
            val params = attributes
            params.gravity = getGravity()
            //子类需要定制宽高就重写这个方法
            setLayoutParams(params)
            attributes = params
            setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
        }
    }

    protected open fun setLayoutParams(params: WindowManager.LayoutParams) {}

    protected abstract fun getLayoutRes(): Int

    protected open fun getStyle() = R.style.Theme_Material_Dialog_NoActionBar_MinWidth

    protected open fun getBackgroundRes(): Int? {
        return R.color.white
    }

    /**
     * 弹出位置
     *
     * @return Gravity
     */
    protected open fun getGravity() = Gravity.CENTER

    protected abstract fun init(savedInstanceState: Bundle?)

    /**
     * 用法： 先调用syncLifeCycle()， 然后在需要的时候调用show()
     */
    open fun syncLifeCycle(fragment: Fragment): BaseDialogFragment {
        if (syncLifecycle) return this
        doSync(fragment, fragment.childFragmentManager)
        syncLifecycle = true
        return this
    }

    open fun syncLifeCycle(activity: FragmentActivity): BaseDialogFragment {
        if (syncLifecycle) return this
        doSync(activity, activity.supportFragmentManager)
        syncLifecycle = true
        return this
    }

    private fun doSync(lifecycleOwner: LifecycleOwner, fragmentManager: FragmentManager) {
        if (showLiveData == null) {
            showLiveData = MutableLiveData()
        }
        showLiveData?.apply {
            observe(lifecycleOwner, Observer {
                if (it) {
                    super.show(fragmentManager, lifecycleOwner.javaClass.simpleName)
                } else {
                    super.dismiss()
                }
            })
        }
    }

    open fun dismissWhenRecreate() = false

}